// 验证
const { body, query, validationResult } = require("express-validator");

const User = require("../model/system/User");

const { validate } = require("../middleware/validation");
const md5 = require("../util/md5");

// 登录验证
const validateLogin = [
  validate([
    body("user.username").notEmpty().withMessage("用户名不能为空"),
    body("user.password").notEmpty().withMessage("密码不能为空"),
  ]),
  validate([
    body("user.username").custom(async (value, { req }) => {
      const user = await User.findOne({ username: value }).select([
        "username",
        "password",
        "email",
      ]);
      if (!user) {
        return Promise.reject("用户不已存在");
      }
      //   将用户绑定到req.user上
      req.user = user;
    }),
  ]),
  validate([
    body("user.password").custom(async (password, { req }) => {
      const user = req.user;
      if (user.password !== md5(password)) {
        return Promise.reject("密码错误");
      }
    }),
  ]),
];

// 注册验证
const validateRigister = validate([
  body("user.username")
    .notEmpty()
    .withMessage("用户名不能为空")
    .bail()
    .custom((value) => {
      console.log(value, "yonghuming");
      return User.findOne({ username: value }).then((user) => {
        if (user) {
          return Promise.reject("用户名已存在");
        }
      });
    }),
  body("user.username")
    .isLength({ min: 1 })
    .withMessage("用户名长度不能小于3位"),
  body("user.password").notEmpty().withMessage("密码不能为空"),
  body("user.password").isLength({ min: 6 }).withMessage("密码长度不能小于6位"),
  body("user.email").isEmail().withMessage("请输入正确的邮箱地址"),
]);

module.exports = {
  validateLogin,
  validateRigister,
};
